package com.app.controller.miniProgram;


import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.LoginVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;

@RestController
@Data
@Controller
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    UserService userService;


    @PostMapping("/updateUser")//    修改用户信息
    public Result<Object> insertPlant(
            @RequestParam("faceUrl") String faceUrl,
            @RequestParam("userName") String userName,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        String uid = TokenUtils.nothingness(token);
        if (uid == null) {
            return Result.error(405, "token不存在");
        }
        UserModel userModel = userService.getUserById(Integer.parseInt(uid));
        if (userModel == null) {
            return Result.error(405, "用户不存在");
        }
        LoginVo loginVo = new LoginVo();
        UserModel userModel1 = new UserModel();
        userModel1.setId(userModel.getId());
        userModel1.setUserName(userName);
        userModel1.setFaceUrl(faceUrl);
        try {
            userModel1.setUpTime(CommonHelp.getNowTimestamp());
            userService.update(userModel1);
            loginVo.setUser(userModel1);
            loginVo.setToken(token);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return Result.success(loginVo);
    }


    //获取openid
    @GetMapping("/login")
    public Result<Object> login(@RequestParam(value = "code") String code) throws LoginException {
        UserModel user = userService.wxLogin(code);
        return Result.success(user);
    }
}